<template>
    <div class="export-container">
        <n-card title="导出项目" class="export-card">
            <n-tabs type="segment" animated>
                <n-tab-pane name="video" tab="视频导出">
                    <n-form ref="formRef" :model="formData" label-placement="left" label-width="100">
                        <n-form-item label="导出格式">
                            <n-select v-model:value="formData.format" :options="videoFormatOptions"
                                placeholder="请选择视频格式" />
                        </n-form-item>

                        <n-form-item label="导出质量">
                            <n-slider v-model:value="formData.quality" :min="1" :max="10" :step="1" :marks="{
                                1: '低',
                                5: '中',
                                10: '高'
                            }" />
                        </n-form-item>

                        <n-form-item label="分辨率">
                            <n-radio-group v-model:value="formData.resolutionType">
                                <n-space>
                                    <n-radio value="original">原始尺寸</n-radio>
                                    <n-radio value="preset">预设尺寸</n-radio>
                                    <n-radio value="custom">自定义</n-radio>
                                </n-space>
                            </n-radio-group>
                        </n-form-item>

                        <n-form-item label="预设尺寸" v-if="formData.resolutionType === 'preset'">
                            <n-select v-model:value="formData.preset" :options="presetOptions"
                                @update:value="updateResolutionFromPreset" />
                        </n-form-item>

                        <n-form-item label="自定义尺寸" v-if="formData.resolutionType === 'custom'">
                            <n-input-group>
                                <n-input-number v-model:value="formData.width" :min="100" :max="3840"
                                    placeholder="宽度" />
                                <n-input-group-label>x</n-input-group-label>
                                <n-input-number v-model:value="formData.height" :min="100" :max="2160"
                                    placeholder="高度" />
                                <n-button @click="keepAspectRatio = !keepAspectRatio"
                                    :type="keepAspectRatio ? 'primary' : 'default'">
                                    <template #icon>
                                        <n-icon>
                                            <LinkOutline v-if="keepAspectRatio" />
                                            <CloseCircleOutline v-else />
                                        </n-icon>
                                    </template>
                                </n-button>
                            </n-input-group>
                        </n-form-item>

                        <n-form-item label="帧率">
                            <n-input-number v-model:value="formData.fps" :min="1" :max="60" :step="1" />
                        </n-form-item>

                        <n-form-item label="位置">
                            <n-select v-model:value="formData.location" :options="locationOptions" />
                        </n-form-item>
                    </n-form>
                </n-tab-pane>

                <n-tab-pane name="gif" tab="GIF动图">
                    <n-form :model="formData" label-placement="left" label-width="100">
                        <n-form-item label="尺寸">
                            <n-input-group>
                                <n-input-number v-model:value="formData.gifWidth" :min="50" :max="800"
                                    placeholder="宽度" />
                                <n-input-group-label>x</n-input-group-label>
                                <n-input-number v-model:value="formData.gifHeight" :min="50" :max="800"
                                    placeholder="高度" />
                            </n-input-group>
                        </n-form-item>

                        <n-form-item label="帧率">
                            <n-select v-model:value="formData.gifFps" :options="gifFpsOptions" />
                        </n-form-item>

                        <n-form-item label="循环">
                            <n-select v-model:value="formData.loop" :options="loopOptions" />
                        </n-form-item>

                        <n-form-item label="质量">
                            <n-slider v-model:value="formData.gifQuality" :min="1" :max="10" :step="1" />
                        </n-form-item>
                    </n-form>
                </n-tab-pane>

                <n-tab-pane name="image" tab="图片序列">
                    <n-form :model="formData" label-placement="left" label-width="100">
                        <n-form-item label="图片格式">
                            <n-select v-model:value="formData.imageFormat" :options="imageFormatOptions" />
                        </n-form-item>

                        <n-form-item label="分辨率">
                            <n-input-group>
                                <n-input-number v-model:value="formData.imageWidth" :min="100" :max="3840"
                                    placeholder="宽度" />
                                <n-input-group-label>x</n-input-group-label>
                                <n-input-number v-model:value="formData.imageHeight" :min="100" :max="2160"
                                    placeholder="高度" />
                            </n-input-group>
                        </n-form-item>

                        <n-form-item label="帧间隔">
                            <n-input-number v-model:value="formData.frameInterval" :min="1" :step="1"
                                placeholder="每隔多少帧导出一张" />
                        </n-form-item>

                        <n-form-item label="压缩质量" v-if="formData.imageFormat === 'jpg'">
                            <n-slider v-model:value="formData.jpgQuality" :min="1" :max="100" :step="1" :marks="{
                                1: '1%',
                                50: '50%',
                                100: '100%'
                            }" />
                        </n-form-item>
                    </n-form>
                </n-tab-pane>
            </n-tabs>

            <template #action>
                <n-space justify="end">
                    <n-button @click="cancel">取消</n-button>
                    <n-button @click="showPreview" :disabled="isExporting">预览</n-button>
                    <n-button type="primary" @click="startExport" :loading="isExporting">
                        {{ isExporting ? '导出中...' : '开始导出' }}
                    </n-button>
                </n-space>
            </template>
        </n-card>

        <n-modal v-model:show="showPreviewModal" preset="card" title="导出预览" :bordered="false" style="width: 600px">
            <div class="preview-container">
                <div class="preview-image">
                    <img src="https://placeholder.pics/svg/500x300" alt="预览" />
                </div>
                <div class="preview-info">
                    <p><strong>格式:</strong> {{ formData.format }}</p>
                    <p><strong>分辨率:</strong> {{ formData.width }}x{{ formData.height }}</p>
                    <p><strong>帧率:</strong> {{ formData.fps }}</p>
                    <p><strong>预计大小:</strong> {{ estimatedSize }}</p>
                    <p><strong>预计时长:</strong> {{ formatDuration(projectDuration) }}</p>
                </div>
            </div>
            <template #action>
                <n-button type="primary" @click="startExport">
                    开始导出
                </n-button>
            </template>
        </n-modal>

        <n-modal v-model:show="showExportCompleteModal" preset="dialog" title="导出完成" positive-text="打开文件"
            negative-text="关闭" @positive-click="openExportedFile" @negative-click="closeExportCompleteModal">
            <template #icon>
                <n-icon color="#18a058">
                    <CheckmarkCircleOutline />
                </n-icon>
            </template>
            <div>您的项目已成功导出到:</div>
            <div class="export-path">{{ exportedFilePath }}</div>
        </n-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
    NCard,
    NTabs,
    NTabPane,
    NForm,
    NFormItem,
    NSelect,
    NSlider,
    NRadioGroup,
    NRadio,
    NInputNumber,
    NButton,
    NSpace,
    NInputGroup,
    NInputGroupLabel,
    NIcon,
    NModal,
    useMessage
} from 'naive-ui'
import {
    LinkOutline,
    CheckmarkCircleOutline,
    CloseCircleOutline
} from '@vicons/ionicons5'
import type { FormInst } from 'naive-ui'

const router = useRouter()
const message = useMessage()
const formRef = ref<FormInst | null>(null)
const keepAspectRatio = ref(true)
const isExporting = ref(false)
const showPreviewModal = ref(false)
const showExportCompleteModal = ref(false)
const exportedFilePath = ref('')
const projectDuration = ref(120) // 项目时长，单位秒

// 表单数据
const formData = reactive({
    // 视频导出
    format: 'mp4',
    quality: 8,
    resolutionType: 'original',
    preset: '720p',
    width: 1280,
    height: 720,
    fps: 30,
    location: 'desktop',

    // GIF导出
    gifWidth: 480,
    gifHeight: 270,
    gifFps: 10,
    loop: 0, // 0表示无限循环
    gifQuality: 7,

    // 图片序列
    imageFormat: 'png',
    imageWidth: 1920,
    imageHeight: 1080,
    frameInterval: 1,
    jpgQuality: 85
})

// 选项
const videoFormatOptions = [
    { label: 'MP4 (H.264)', value: 'mp4' },
    { label: 'WebM (VP9)', value: 'webm' },
    { label: 'MOV (QuickTime)', value: 'mov' }
]

const presetOptions = [
    { label: '480p (SD)', value: '480p', width: 854, height: 480 },
    { label: '720p (HD)', value: '720p', width: 1280, height: 720 },
    { label: '1080p (Full HD)', value: '1080p', width: 1920, height: 1080 },
    { label: '1440p (2K)', value: '1440p', width: 2560, height: 1440 },
    { label: '2160p (4K)', value: '2160p', width: 3840, height: 2160 }
]

const locationOptions = [
    { label: '桌面', value: 'desktop' },
    { label: '项目文件夹', value: 'project' },
    { label: '自定义位置...', value: 'custom' }
]

const gifFpsOptions = [
    { label: '10 FPS', value: 10 },
    { label: '15 FPS', value: 15 },
    { label: '20 FPS', value: 20 },
    { label: '25 FPS', value: 25 },
    { label: '30 FPS', value: 30 }
]

const loopOptions = [
    { label: '无限循环', value: 0 },
    { label: '循环一次', value: 1 },
    { label: '循环两次', value: 2 },
    { label: '循环三次', value: 3 }
]

const imageFormatOptions = [
    { label: 'PNG (无损)', value: 'png' },
    { label: 'JPG (有损)', value: 'jpg' },
    { label: 'WebP', value: 'webp' }
]

// 计算预计文件大小
const estimatedSize = computed(() => {
    // 这只是一个粗略的估计，实际文件大小会因编码器和内容而异
    const bitrate = formData.quality * 1000 * 1000 // 质量 * 1Mbps
    const bytes = (bitrate / 8) * projectDuration.value

    if (bytes < 1024 * 1024) {
        return `${(bytes / 1024).toFixed(2)} KB`
    } else if (bytes < 1024 * 1024 * 1024) {
        return `${(bytes / (1024 * 1024)).toFixed(2)} MB`
    } else {
        return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`
    }
})

// 更新分辨率（从预设）
const updateResolutionFromPreset = (value: string) => {
    const preset = presetOptions.find(option => option.value === value)
    if (preset) {
        formData.width = preset.width
        formData.height = preset.height
    }
}

// 格式化时长
const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 显示预览
const showPreview = () => {
    showPreviewModal.value = true
}

// 开始导出
const startExport = () => {
    showPreviewModal.value = false
    isExporting.value = true

    // 模拟导出过程
    setTimeout(() => {
        isExporting.value = false
        exportedFilePath.value = `C:\\Users\\用户\\Desktop\\项目_${new Date().getTime()}.${formData.format}`
        showExportCompleteModal.value = true
    }, 3000)
}

// 打开导出的文件
const openExportedFile = () => {
    message.success('打开文件')
    // 这里应该调用Electron API打开文件
}

// 关闭导出完成对话框
const closeExportCompleteModal = () => {
    showExportCompleteModal.value = false
}

// 取消导出
const cancel = () => {
    router.back()
}
</script>

<style lang="scss" scoped>
.export-container {
    padding: 24px;
    min-height: 100vh;
    background-color: var(--body-color);

    .export-card {
        max-width: 800px;
        margin: 0 auto;
    }

    .preview-container {
        display: flex;
        flex-direction: column;
        gap: 20px;

        .preview-image {
            background-color: #f5f5f5;
            border-radius: 4px;
            overflow: hidden;
            display: flex;
            justify-content: center;

            img {
                max-width: 100%;
                object-fit: contain;
            }
        }

        .preview-info {
            p {
                margin: 8px 0;
            }
        }
    }

    .export-path {
        margin-top: 8px;
        padding: 8px 12px;
        background-color: var(--body-color);
        border-radius: 4px;
        font-family: monospace;
        word-break: break-all;
    }
}

/* 响应式调整 */
@media (max-width: 768px) {
    .export-container {
        padding: 16px;

        .export-card {
            max-width: 100%;
        }
    }
}
</style>